package com.ark.service.impl;

import com.ark.constant.JwtClaimsConstant;
import com.ark.constant.MessageConstant;
import com.ark.dto.UserLoginDTO;
import com.ark.entity.User;
import com.ark.exception.LoginFailedException;
import com.ark.mapper.UserMapper;
import com.ark.properties.JwtProperties;
import com.ark.properties.WeChatProperties;
import com.ark.service.UserService;
import com.ark.utils.HttpClientUtil;
import com.ark.utils.JwtUtil;
import com.ark.vo.UserLoginVO;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    private final JwtProperties jwtProperties;
    private final WeChatProperties weChatProperties;
    private final UserMapper userMapper;

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {


        //1.调用微信接口，获取微信用户id
        String openid = getOpenid(userLoginDTO.getCode());

        //2.如果openid为空，则失败
        if(openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //3.当前用户是否为新用户-根据openid
        User user = userMapper.getUserByOpenid(openid);
        if(user==null){
            //新用户，自动注册
            user = User.builder()
                    .openid(openid)
                    .build();
            userMapper.insert(user);
        }


        //4.如果是，自动完成注册

        //为用户生成jwt令牌
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());

        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        return UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
    }

    private String getOpenid(String code) {
        HashMap<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppId());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");

        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(json, JsonObject.class);
        return jsonObject.get("openid").getAsString();
    }
}
